<template>
  <div ref="chart" class="chart" :style="{ height: '400px' }"></div>
</template>

<script setup>
import { onMounted, ref, onBeforeUnmount } from 'vue';
import * as echarts from 'echarts';
import { getAllCourses } from "@/apis/course.js";

// 使用 ref 来定义 categoriesData
const categoriesData = ref([]);

const AllCourses = async () => {
  const res = await getAllCourses();
  categoriesData.value = res.data; // 更新响应式数据
}

const chart = ref(null);
let myChart = null;

const initChart = () => {
  myChart = echarts.init(chart.value);

  // 提取类别、课程数量和价格
  const categories = categoriesData.value.map(category => category.categoryName);
  const courseCounts = categoriesData.value.map(category => category.coursesList.length);
  const averagePrices = categoriesData.value.map(category => {
    const totalPrice = category.coursesList.reduce((sum, course) => sum + course.price, 0);
    return category.coursesList.length > 0 ? (totalPrice / category.coursesList.length) : 0; // 防止除以零
  });

  const options = {
    title: {
      text: '课程分类统计',
      left: 'center',
      top: '20px',
      textStyle: {
        fontSize: 24,
        fontWeight: 'bold',
        color: '#333'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {
      data: ['课程数量', '平均价格'],
      bottom: '10px'
    },
    xAxis: {
      type: 'category',
      data: categories,
      axisLabel: {
        fontSize: 14,
        color: '#666'
      }
    },
    yAxis: [
      {
        type: 'value',
        name: '课程数量',
        position: 'left',
        axisLabel: {
          formatter: '{value}',
          fontSize: 14,
          color: '#666'
        }
      },
      {
        type: 'value',
        name: '平均价格',
        position: 'right',
        axisLabel: {
          formatter: '{value} 元',
          fontSize: 14,
          color: '#666'
        }
      }
    ],
    series: [
      {
        name: '课程数量',
        type: 'bar',
        data: courseCounts,
        itemStyle: {
          color: '#4B9CD3'
        },
        emphasis: {
          focus: 'series'
        }
      },
      {
        name: '平均价格',
        type: 'line',
        yAxisIndex: 1,
        data: averagePrices,
        itemStyle: {
          color: '#F39C12'
        },
        smooth: true
      }
    ]
  };

  myChart.setOption(options);
};

onMounted(async () => {
  await AllCourses(); // 等待获取课程数据
  initChart(); // 初始化图表

  // 监听窗口变化
  window.addEventListener('resize', myChart.resize);
});

onBeforeUnmount(() => {
  // 销毁图表实例
  myChart.dispose();
});
</script>

<style scoped>
.chart {
  width: 100%;
}
</style>
